using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyThings : MonoBehaviour
{
    [Header("泡泡停留数秒")] [SerializeField] private float paopaoWaitCount;
    [Header("上升速度")] [SerializeField] private float flySpeed;
    [Header("上升秒数")][SerializeField] private float flyCount;
    
    [Header("开启点对点传送")] [SerializeField] private bool startPointToPoint;
    [Header("点对点上升秒数")] [SerializeField] private float pointToPointFlyCount;
    private Vector2 start;
    [SerializeField] Transform target;
    [Header("上升后停留秒数")] [SerializeField] private float stayDuration;
    private Transform box;

    private void Start()
    {
        start = transform.position;
        // box = transform.GetChild(0);
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.tag == "paopao")
        {
            StartMove();
        }
    }

    private IEnumerator PointToPoint(float duration)
    {
        yield return new WaitForSeconds(paopaoWaitCount);
        float elapsedTime = 0;
        while (elapsedTime < duration)
        {
            float t = elapsedTime / duration;
            transform.position = Vector2.Lerp(start, target.position, t);
            elapsedTime += Time.deltaTime;
            yield return null;
        }
        transform.position = target.position;
        yield return new WaitForSeconds(stayDuration);

        elapsedTime = 0;
        while (elapsedTime < duration)
        {
            float t = elapsedTime / duration;
            transform.position = Vector2.Lerp(target.position, start, t);
            elapsedTime += Time.deltaTime;
            yield return null;
        }

        transform.position = start;

    }

    private IEnumerator UpToTarget(float duration)
    {
        yield return new WaitForSeconds(paopaoWaitCount);
        
        float count = duration;
        while (count >= 0)
        {
            transform.position += Vector3.up * (flySpeed * Time.deltaTime);
            count -= Time.deltaTime;
            yield return null;
        }
        
        yield return new WaitForSeconds(stayDuration);

        count = duration;
        while (count >= 0)
        {
            transform.position += Vector3.down * (flySpeed * Time.deltaTime);
            count -= Time.deltaTime;
            yield return null;
        }
        
        transform.position = start;
    }

    private void StartMove()
    {
        Debug.Log("1");
        if (startPointToPoint)
        {
            StartCoroutine(PointToPoint(pointToPointFlyCount));
        }
        else
        {
            StartCoroutine(UpToTarget(flyCount));
        }
    }
}